#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUFSIZE	128


int main(void)
{
    int pfd[2] = {}; // 管道通信文件描述符
    pid_t pid;

    if (-1 == pipe(pfd)) {
        perror("pipe()");
        return 1;
    }

    pid = fork();

    if (-1 == pid) {
        perror("fork()");
        return 1;
    }

    if (0 == pid) {
        char buf[BUFSIZE] = {};
        int ret;

        close(pfd[1]); // 子进程关闭管道写端

        while ((ret = read(pfd[0], buf, BUFSIZE)) > 0) {
            write(1, buf, ret);
            memset(buf, 0, BUFSIZE);
        }

        if (-1 == ret) {
            perror("read()");
            return 1;
        }

        close(pfd[0]);
        return 0;
    }

    close(pfd[0]); // 父进程关闭管道读端

    sleep(1);
    write(pfd[1], "hello world\n", 12);
    sleep(1);

    close(pfd[1]);

    wait(NULL);

    return 0;
}

